package ro.isdc.vms.misc.batch.tasklet;

import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.UnexpectedJobExecutionException;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;

/**
 * Deletes files from an array of resources, so a pattern can be used in
 * configuration, e.g. <code>resources="/home/batch/job/**"</code>
 * 
 * @author Andrei.Chirila / ISDC! Romania
 * @version 1.0.0
 * @date Jul 21, 2009
 */
public class FileDeletingTasklet implements Tasklet, InitializingBean {

	private Resource[] resources;

	public RepeatStatus execute(final StepContribution contribution, final ChunkContext context) throws Exception {
		for (Resource resource : resources) {
			boolean deleted = resource.getFile().delete();
			if (!deleted) {
				throw new UnexpectedJobExecutionException("Could not delete file " + resource);
			}
		}
		return RepeatStatus.FINISHED;
	}

	public void setResources(final Resource[] resources) {
		this.resources = resources;
	}

	public void afterPropertiesSet() throws Exception {
	  if (resources == null) {
	    throw new IllegalStateException("Resources must be set");
	  }
	}

}
